package com.vcs.basicserviceclient.controller;

import com.vcs.basicapi.domain.User;

import com.vcs.basicserviceclient.hystrix.BasicRibbonClientHystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collection;

/**
 * @ProjectName: spring-cloud-fosun
 * @Package: com.vcs.basicserviceclient.controller
 * @ClassName: BasicRibbonController
 * @Author: zhangs
 * @Email: 853632587@qq.com
 * @Description: 基础负载均衡
 * @Date: 2020/12/3 15:57
 * @Version: 1.0
 */
@RestController
public class BasicRibbonController {

    /**
     * 负载均衡器客户端
     */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Value("${provider.service.name}")
    private String providerServiceName;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("")
    public String index() throws IOException {

        User user = new User();
        user.setName("测试");
        user.setAge(1);
        // 选择指定的 service Id
        ServiceInstance serviceInstance = loadBalancerClient.choose(providerServiceName);

        return loadBalancerClient.execute(providerServiceName, serviceInstance, instance -> {

            //服务器实例，获取 主机名（IP） 和 端口
            String host = instance.getHost();
            int port = instance.getPort();
            String url = "http://" + host + ":" + port + "/user/save";
            RestTemplate restTemplate = new RestTemplate();

            return restTemplate.postForObject(url, user, String.class);

        });

    }

    /**
     * 调用 basic-service-provider "/user/list" REST 接口，并且直接返回内容
     * 增加 短路功能
     */
    @GetMapping("/basic-service-provider/user/list")
    public Collection<User> getUsersList() {
        return new BasicRibbonClientHystrixCommand(providerServiceName, restTemplate).execute();
    }

}
